﻿using IpToBlack.Models;
using IpToBlack.PUB;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IpToBlack
{
    public class IpTool
    {
        public static void ScanWinLog()
        {
            try
            {
                long lastID = 0;
                var lastid = PUB.gFunc.sysGetVar("sys_log_maxid");
                if (!string.IsNullOrEmpty(lastid))
                {
                    lastID = Convert.ToInt64(lastid);
                }


                DB db = new DB();

                EventLog log = new EventLog();
                log.Log = "Application"; //"Application"、"System"、"Security" Security 安全日志

                // 查询最近的事件
                //D为18456（登录成功）、18457（登录失败）和18458（登录尝试）的事件
                foreach (EventLogEntry entry in log.Entries)
                {
                    if (entry.Source.Equals("MSSQLSERVER") &&
                        (entry.EventID == 18456 || entry.EventID == 18457 || entry.EventID == 18458) &&
                        (entry.InstanceId > lastID))
                    {
                        Console.WriteLine("Entry Type: " + entry.EntryType);
                        Console.WriteLine("Time Generated: " + entry.TimeGenerated);
                        Console.WriteLine("Message: " + entry.Message);

                        PUB.gFunc.WriteLog($"Date: {entry.TimeGenerated}");
                        PUB.gFunc.WriteLog($"User: {string.Join("-", entry.ReplacementStrings)}");

                        PUB.gFunc.WriteLog($"Message: " + entry.Message);

                        var ip = PUB.gFunc.GetTextToIP(entry.Message);
                        PUB.gFunc.WriteLog($"IP: " + ip);

                        if (!string.IsNullOrEmpty(ip))
                        {
                            var item99 = db.iSugar.Queryable<sys_t_ip>().Where(b => b.ip == ip).First();
                            if (item99 != null)
                            {
                                item99.qty = item99.qty + 1;
                                db.UpdateModel(item99);
                            }
                            else
                            {
                                var item1 = new sys_t_ip()
                                {
                                    ip = ip,
                                    qty = 1,
                                    b_flag = "0",
                                };
                                db.InsertModel(item1);
                            }
                        }

                    }

                }

                // 获取日志中的最大事件ID
                long maxId = 0;
                foreach (EventLogEntry entry in log.Entries)
                {
                    if (entry.InstanceId > maxId)
                    {
                        maxId = entry.InstanceId;
                    }
                }

                PUB.gFunc.sysPutVar("sys_log_maxid", maxId.ToString());
                IP2Fw2();
            }
            catch (Exception er)
            {
                PUB.gFunc.WriteLog($"错误: " + er.Message + er.StackTrace);
            }
        }
        public static void IP2Fw1()
        {
            try
            {
                DB db = new DB();
                var item99 = db.iSugar.Queryable<sys_t_ip>().Where(b => b.b_flag == "0" && b.qty > 5).ToList();
                List<string> ipList = new();
                foreach (sys_t_ip item in item99)
                {
                    if (gFwM.AddIPBlockRule1(item.ip))
                    {
                        item.b_flag = "1";
                        db.UpdateModel(item);
                    }
                }

            }
            catch (Exception er)
            {
                PUB.gFunc.WriteLog($"错误: " + er.Message + er.StackTrace);
            }

        }
        public static void IP2Fw2()
        {
            try
            {
                DB db = new DB();
                var item99 = db.iSugar.Queryable<sys_t_ip>().Where(b => b.b_flag == "0" && b.qty > 5).ToList();
                List<string> ipList = new();
                foreach (sys_t_ip item in item99)
                {
                    ipList.Add(item.ip);
                }
                if (ipList.Count > 0)
                {
                    if (gFwM.AddIPBlockRule3(ipList))
                    {
                        for (int i = 0; i < item99.Count; i++)
                        {
                            item99[i].b_flag = "1";
                        }
                        db.iSugar.Updateable(item99).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
                    }
                }

            }
            catch (Exception er)
            {
                PUB.gFunc.WriteLog($"错误: " + er.Message + er.StackTrace);
            }

        }

    }
}
